﻿CREATE PROCEDURE [dbo].[WriteOffLinesDelete]
(--списание товара
	@Original_Id int,
	@Original_MD datetime
)
AS
DECLARE @strMsg nvarchar(500), @intErrCode int, @intRet int, @intRowCount int
DECLARE @intGoodsDocLineId int

SET NOCOUNT ON
IF (@Original_Id Is Null) OR (@Original_MD Is Null) 
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

SELECT @intGoodsDocLineId = GoodsDocLineId 
FROM CD.RepriceWriteoffLines WHERE Id = @Original_Id AND MD = @Original_MD
IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 2, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

BEGIN TRAN

DELETE FROM CD.RepriceWriteoffLines WHERE Id = @Original_Id

SELECT @intErrCode = @@error, @intRowCount = @@rowcount
IF @intErrCode <> 0 
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	RETURN @intErrCode
END
IF (@intRowCount <> 1)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 3, 
	@strMsg = 'Запись из таблицы списания/переоценки не удалена!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

	SET NOCOUNT OFF;

DELETE FROM [CA].[GoodsDocLines] WHERE Id = @intGoodsDocLineId

SELECT @intErrCode = @@error, @intRowCount = @@rowcount

	SET NOCOUNT ON;

IF @intErrCode <> 0 
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	RETURN @intErrCode
END
IF (@intRowCount <> 1)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 4, 
	@strMsg = 'Запись из таблицы товародвижения не удалена!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

COMMIT TRAN

RETURN 0